import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Alert, Skeleton, Avatar, Tag, Popover, message, Tooltip, Divider } from 'antd';
import { useRequest } from '@/hooks';
import { fetchEmployeeInfo, fetchEntryPersonnelInfo } from '@/pages/EntryManage/services';
import moment from 'moment';
import IconFont from '@/components/IconFont';
import MoreOperateModal from '@/pages/EntryManage/components/MoreOperateModal';
import { history } from 'umi'
import { ENTRY_STATUS_MAP, MATERIAL } from '@/pages/EntryManage/utils';
import { eventTrack } from '@/utils/track';
import { size } from 'lodash';
import authHelper from '@/utils/auth/helper';
import styles from './index.less';

const { checkCode } = authHelper;

/**
 * 员工的基本信息面板
 * @param employeeCode 员工id
 * @param isShowControls 是否显示控制栏户籍
 * @param props
 * @returns {*}
 * @constructor
 */
const EmployeeCard = ({ employeeCode, isShowControls, location, ...props }) => {
    const task = location?.query?.task; // 从消息进来的时候，有这个tab属性，其他的没有，只作用于消息进来的时候弹窗弹出

    const [modalEntryOperateType, setModalEntryOperateType] = useState(1);
    const [modalVisible, setModalVisible] = useState(false);

    const {
        data: employeeInfoData,
        error: fetchEmployeeInfoError,
        loading: fetchEmployeeInfoLoading,
        refresh: refreshEmployeeInfo
    } = useRequest(() => fetchEmployeeInfo(employeeCode), {
        cacheKey: `entry-employee-info-${employeeCode}`,
        refreshDeps: [employeeCode],
        ready: !!employeeCode,
        formatResult: res => {
            if (res.code === 10000) {
                if (res?.data?.applyEntryDateStatus === 'waitfor' && task && task === 'applyModifyEntryDate') {
                    setModalEntryOperateType(2);
                    setModalVisible(true);
                }
                return res.data;
            }
            message.error(res.msg);
            // history.push('/office/personnelManagement/onboardAndLeave/entryManage/waitEntry');
            return null;
        }
    });
    const {
        isSignedContract,
        entryStatus,
        recruitDirectorCode,
        assignEmployeeList = [],
        step,
        entryPersonnelCode,
        organizationCode,
        contractOrganizationCode,
        idPhoto,
        employeeName,
        processDescription,
        entryDate,
        dutyName,
        rankValue,
        organizationName,
        contractOrganizationName,
        modifyHandlerButtonVisible
    } = employeeInfoData || {};

    const canAction = entryStatus && entryStatus < 100;
    const isShowModifyHandlerBtn = modifyHandlerButtonVisible;
    const user = JSON.parse(localStorage.getItem('user') || '{}');

    // 取合同地址, 合同地址在入职材料接口里面的附件列表中
    const { data: signedContractFileUrl } = useRequest(
        () =>
            fetchEntryPersonnelInfo({
                entryPersonnelCode: employeeCode,
                organizationCode
            }),
        {
            cacheKey: `signed-contract-file-url-${employeeCode}`,
            ready: !!employeeInfoData,
            refreshDeps: [employeeCode],
            formatResult: res => {
                if (res.code === 10000) {
                    if (res.data?.resCombineBusinessResourceDtoLocalList?.length) {
                        const signedContractItem = res.data.resCombineBusinessResourceDtoLocalList.filter(
                            item => item.categoryCode === MATERIAL.SIGNED_CONTRACT
                        );
                        return signedContractItem?.[0]?.urlList?.[0]?.url;
                    }
                }
                return null;
            }
        }
    );

    // 数据获取错误处理
    if (fetchEmployeeInfoError || (!fetchEmployeeInfoLoading && !employeeInfoData)) {
        return (
            <Alert
                style={{ marginBottom: '20px' }}
                type="error"
                message={fetchEmployeeInfoError?.msg || '员工数据加载失败'}
            />
        );
    }

    // 按钮跟随状态变化而变化
    const renderStatusButton = record => {
        let isShowBtn = false;
        if (size(assignEmployeeList?.filter(item => item?.employeeCode === user.employeeCode)) > 0) {
            // 登录人在处理列表里面
            isShowBtn = true;
        } else if (user.employeeCode === recruitDirectorCode) {
            // 登录人是招聘负责人，但是不在处理列表里面，状态为1的时候需要按钮
            if (entryStatus === 1) {
                isShowBtn = true;
            }
        }

        if (isShowBtn === true && checkCode(ENTRY_STATUS_MAP[entryStatus].code)) {
            return (
                <>
                    <Tooltip
                        title={`${ENTRY_STATUS_MAP[entryStatus]?.tipText || ENTRY_STATUS_MAP[entryStatus]?.name}${
                            step < 2 ? '，待完成入职引导后才能接收' : ''
                        }`}
                    >
                        <IconFont
                            icon={ENTRY_STATUS_MAP[entryStatus]?.icon}
                            disabled={step < 2} // 待入职员工需要填写数据才能接收
                            className={styles.iconButton}
                            onClick={async () => {
                                await eventTrack({
                                    eventName:
                                        'personnel_management_onboard_and_leave_entry_manage_wait_entry_operator_click',
                                    pageName: 'personnel_management_onboard_and_leave',
                                    eventProps: {
                                        click_context: `${record.employeeName}-${ENTRY_STATUS_MAP[entryStatus]
                                            ?.tipText || ENTRY_STATUS_MAP[entryStatus]?.name}`
                                    }
                                });
                                const pathname = ENTRY_STATUS_MAP[entryStatus]?.url;
                                const param = { entryPersonnelCode, organizationCode, contractOrganizationCode };
                                if (pathname) {
                                    history.push({
                                        pathname,
                                        query: param
                                    });
                                }
                            }}
                        />
                    </Tooltip>
                    {user.employeeCode === recruitDirectorCode && <Divider type="vertical" />}
                </>
            );
        }
        return null;
    };
    return (
        <div className={styles.employeeCard} {...props}>
            {/* 使用 employeeInfoData 做loading 条件, 是想使用缓存, 有缓存信息就直接显示 */}
            <Skeleton loading={!employeeInfoData} active avatar>
                {employeeInfoData && (
                    <>
                        <Avatar
                            icon="user"
                            src={idPhoto && idPhoto.length > 0 ? idPhoto[0].url : ''}
                            size={66}
                            className={styles.employeeAvatar}
                        />
                        <div className={styles.employeeContent}>
                            <div>
                                <h3 className={styles.employeeName}>{employeeName}</h3>
                                {isShowControls && processDescription && (
                                    <Tag className={styles.employeeStatus}>{processDescription}</Tag>
                                )}
                            </div>
                            <div className={styles.employeeMeta}>
                                <div className={styles.employeeMetaItem} title="入职时间">
                                    <IconFont icon="icontimeAdjusted" />
                                    {moment(entryDate).format('YYYY-MM-DD')}
                                </div>
                                <div className={styles.employeeMetaItem} title="岗位/职级">
                                    <IconFont icon="iconlist_work_icon_default1" />
                                    {dutyName}/{rankValue}
                                </div>
                                <div className={styles.employeeMetaItem} title="所在组织机构">
                                    <IconFont icon="iconswitch_guideview_icon_default" />
                                    {organizationName}
                                </div>
                                <div className={styles.employeeMetaItem} title="行政机构">
                                    <IconFont icon="iconbank-fill" style={{ fontSize: 12 }} />
                                    {contractOrganizationName}
                                </div>
                            </div>
                        </div>
                        <div className={styles.employeeControls}>
                            {isShowControls && (
                                <>
                                    <Popover content="下载合同">
                                        {signedContractFileUrl ? (
                                            <a
                                                className={styles.employeeControlsItem}
                                                href={signedContractFileUrl}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                            >
                                                <IconFont icon="iconchakanfabuxinxi" />
                                            </a>
                                        ) : null}
                                    </Popover>
                                    {renderStatusButton(employeeInfoData)}
                                    {canAction && (
                                        <>
                                            {/* 登录人员是招聘负责人才能有更多的操作 */}

                                            {isShowModifyHandlerBtn && (
                                                <Tooltip
                                                    title={
                                                        size(assignEmployeeList) > 1
                                                            ? '多个处理人不能指派'
                                                            : '修改处理人'
                                                    }
                                                >
                                                    <IconFont
                                                        disabled={size(assignEmployeeList) > 1} // 多个处理人不能指派
                                                        icon="iconzhidingfuzeren1"
                                                        className={styles.iconButton}
                                                        onClick={() => {
                                                            setModalEntryOperateType(1);
                                                            setModalVisible(true);
                                                        }}
                                                    />
                                                </Tooltip>
                                            )}
                                            {user.employeeCode === recruitDirectorCode && (
                                                <>
                                                    {isShowModifyHandlerBtn && <Divider type="vertical" />}
                                                    <Tooltip
                                                        title={
                                                            employeeInfoData?.applyEntryDateStatus === 'waitfor'
                                                                ? '确认入职时间'
                                                                : '修改入职时间'
                                                        }
                                                    >
                                                        <IconFont
                                                            disabled={entryStatus > 5 || isSignedContract === 1} // 之前逻辑是办理入职完或签订劳动合同不允许在修改入职时间
                                                            icon="iconxiugairuzhishijian"
                                                            className={styles.iconButton}
                                                            onClick={() => {
                                                                setModalEntryOperateType(2);
                                                                setModalVisible(true);
                                                            }}
                                                        />
                                                    </Tooltip>
                                                    <Divider type="vertical" />
                                                    <Tooltip title="终止入职">
                                                        <IconFont
                                                            disabled={entryStatus > 5 || isSignedContract === 1} // 之前逻辑是非招聘负责人、办理入职完或签订劳动合同不允许终止入职
                                                            icon="iconzhongzhiruzhi1"
                                                            className={styles.iconButton}
                                                            onClick={() => {
                                                                setModalEntryOperateType(3);
                                                                setModalVisible(true);
                                                            }}
                                                        />
                                                    </Tooltip>
                                                </>
                                            )}
                                            {modalVisible && (
                                                <MoreOperateModal
                                                    entryPersonnelCode={employeeCode}
                                                    operateType={modalEntryOperateType}
                                                    visible={modalVisible}
                                                    maskClosable={false}
                                                    onCancel={() => {
                                                        setModalEntryOperateType(-1);
                                                        setModalVisible(false);
                                                    }}
                                                    onOk={({ code, msg }) => {
                                                        if (code === 10000) {
                                                            message.success(msg);
                                                            setModalVisible(false);
                                                            setModalEntryOperateType(-1);
                                                            refreshEmployeeInfo();
                                                        } else {
                                                            message.error(msg);
                                                        }
                                                    }}
                                                />
                                            )}
                                        </>
                                    )}
                                </>
                            )}
                        </div>
                    </>
                )}
            </Skeleton>
        </div>
    );
};

// prop
EmployeeCard.propTypes = {
    employeeCode: PropTypes.string.isRequired,
    isShowControls: PropTypes.bool
};

EmployeeCard.defaultProps = {
    isShowControls: false
};

export default React.memo(EmployeeCard);
